//
//  SwiftNetworkTool.swift
//  AFN的封装
//
//  Created by HM on 16/10/7.
//  Copyright © 2016年 HM. All rights reserved.
//

import UIKit
import AFNetworking

class NetworkTool: AFHTTPSessionManager {
    //swift手写单例
    static let shared: NetworkTool = {
        let tool = NetworkTool()
        //添加支持的服务器返回的数据类型
        tool.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tool
    }()
    
    
    /// 发起网络请求
    ///
    /// - parameter url:         url字符串
    /// - parameter method:      请求方式的字符串
    /// - parameter paramerters: 请求参数的字典
    /// - parameter callBack:    完成回调
    func requet(url: String, method: String, paramerters: [String: Any], callBack: @escaping (Any?) -> ()) {
        
        //请求成功的闭包
        let success = { (task: URLSessionDataTask, responseObject: Any?) in
            callBack(responseObject)
        }
        
        //请求失败的闭包
        let failure = { (task: URLSessionDataTask?, error: Error) in
            print(error)
            callBack(nil)
        }
        
        //发起get请求
        if method == "GET" {
            self.get(url, parameters: paramerters, progress: nil, success: success, failure: failure)
        }
        
        //发起post请求
        if method == "POST" {
            self.post(url, parameters: paramerters, progress: nil, success: success, failure: failure)
        }
    }
}
